package org.eclipse.moquette.parser.netty;

import io.netty.buffer.ByteBuf;
import io.netty.util.AttributeMap;
import org.eclipse.moquette.proto.messages.AbstractMessage;
import org.eclipse.moquette.proto.messages.SubAckMessage;

import java.util.List;

/**
 * Created by alex on 15-5-26.
 */
public class SubAckDecoder extends DemuxDecoder {

    @Override
    void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {

        in.resetReaderIndex();
        SubAckMessage message = new SubAckMessage();
        if (!decodeCommonHeader(message, 0x00, in)) {
            in.resetReaderIndex();
            return;
        }

        int remainingLength = message.getRemainingLength();

        message.setMessageID(in.readUnsignedShort());
        remainingLength -= 2;

        if (in.readableBytes() < remainingLength) {
            in.resetReaderIndex();
            return;
        }

        for (int i = 0; i < remainingLength; i++) {
            byte qos = in.readByte();
            message.addType(AbstractMessage.QOSType.values()[qos]);
        }

        out.add(message);
    }
}
